from quant import Markets, MarketData, OrderBook
from quant.const import Event, Exchange


# ----------链接交易所行情----------
markets = Markets()
markets.add_market('Book', 'Binance', 'btc/usdt')
markets.add_market(Event.Book, Exchange.Binance, 'eth/usdt.swap')
markets.add_market(Event.Trade, Exchange.Okex, 'doge/usdt.swap')


# ----------book的使用----------
def fn1(md: MarketData):
    book: OrderBook = md.data
    print('----------book----------')
    print(book.book_repr(5))  # 打印book的前5档
markets.subscribe('Book', 'Binance', 'eth/usdt.swap', fn1)


# ----------trade的使用----------
def fn2(md: MarketData):
    trade: list = md.data
    for side, price, amount in trade:
        print(side, price, amount)  # 打印每笔交易详情
markets.subscribe('Trade', 'Okex', 'doge/usdt.swap', fn2)


# ----------混合订阅----------
def fn3(md: MarketData):
    if md.event == 'Trade':
        if md.exchange == 'Okex':
            if md.symbol == 'doge/usdt.swap':
                print('Okex doge Trade received')
    else:
        print('other data:')
        print(md.data_id)
        print(md.server_time)
        print(md.recv_time)
markets.subscribe_all(fn3)  # 订阅所有已链接的行情


# ----------book数据结构----------
def fn4(md):
    book = md.data
    price, amount = book.item('bid', 1)
    print(price, amount)  # 买一量价

    for price, amount in book.items('ask'):
        print(price)  # 从卖1开始打印各档价格

    mid = book.get_middle()
    print(mid)  # 中间价
markets.subscribe('Book', 'Binance', 'btc/usdt', fn4)


input(':')  # 阻塞程序，持续运行
 